import axios from "axios";
import {useUserStore} from "@/store/modules/user.js";
import appConfig from "@/config/index.js";
import router from "@/router"

const config = {
    baseURL: appConfig.baseURL,
    timeout: 10000,
    headers: {
        "Content-Type": "application/json",
    },
    withCredentials: true,
}

class Http {
    constructor() {
        this.service = axios.create(config)
        this.init()
    }

    init() {
        this.service.interceptors.request.use((config) => {
            const userStore = useUserStore();
            if (userStore.token) {
                config.headers.Authorization = `Bearer ${userStore.token}`;
            }
            return config;
        })
        this.service.interceptors.response.use(
            (response) => {
                switch (response.data.code) {
                    case 200:
                        return response.data;
                    case 500:
                        // msg
                        return response.data;
                    case 401:
                        const userStore = useUserStore();
                        userStore.logout();
                        router.push("/login");
                        break;
                    default:
                        return Promise.reject(response);
                }
                return response;
            },
            (error) => {
                return Promise.reject(error);
            }
        )
    }

    get(url, params = {}, _config = {}) {
        return this.service.get(url, {params,..._config});
    }

    post(url, data = {}, _config = {}) {
        return this.service.post(url, data, _config);
    }

    put(url, data = {}, _config = {}) {
        return this.service.put(url, data, _config);
    }

    delete(url, params = {}, _config = {}) {
        return this.service.delete(url, {params, ..._config});
    }

    patch(url, data = {}, _config = {}) {
        return this.service.patch(url, data, _config);
    }
}

export default new Http()